package com.haojii.jdo;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.haojii.jdo.orm.many2many.EasytvEntity;
import com.haojii.jdo.orm.many2many.EasytvItem;
import com.haojii.jdo.orm.many2many.User;
import com.haojii.jdo.utils.PMF;

@SuppressWarnings("serial")
public class Many2ManyServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/plain");
		
		UserService userService = UserServiceFactory.getUserService(); 
		 
        String thisURL = req.getRequestURI(); 
        if (req.getUserPrincipal() != null) { 
        	System.out.println(userService.getCurrentUser());
        	System.out.println(userService.getCurrentUser().getAuthDomain());
        	System.out.println(userService.getCurrentUser().getEmail());
        	System.out.println(userService.getCurrentUser().getNickname());
        	System.out.println(userService.getCurrentUser().getUserId());
            resp.getWriter().println("<p>Hello, " + 
                                         req.getUserPrincipal().getName() + 
                                         "!  You can <a href=\"" + 
                                         userService.createLogoutURL(thisURL) + 
                                         "\">sign out</a>.</p>"); 
            
            PersistenceManager pm = PMF.get().getPersistenceManager();
    		
    		User u = new User("137XXXXXXX","jacky.jihao@gmail.com","jacky");
    		Set<Key> interestedEasytvEntities = new HashSet<Key>();
    		u.setInterestedEasytvEntities(interestedEasytvEntities);
    		
    		
    		EasytvEntity ee = new EasytvEntity("24 Season 8", "http://easytv.echinatv.com.cn/ItemDet.aspx?IID=11440");
    		List<EasytvItem> easytvItems = new ArrayList<EasytvItem>();
    		EasytvItem ei = new EasytvItem("1", "http://easytv.echinatv.com.cn/ItemDet.aspx?IID=11440/1.rmdv");
    		easytvItems.add(ei);
    		ee.setItems(easytvItems);
    		
    		Set<Key> watchingUsers = new HashSet<Key>();
    		ee.setWatchingUsers(watchingUsers);
    		
    		ee.getWatchingUsers().add(u.getKey());
    		u.getInterestedEasytvEntities().add(ee.getKey());
    		 	
    		pm.makePersistent(u);
    		pm.makePersistent(ee);
        } else { 
            resp.getWriter().println("<p>Please <a href=\"" + 
                                         userService.createLoginURL(thisURL) + 
                                         "\">sign in</a>.</p>"); 
        } 
		
		
		
		
		resp.getWriter().println("Hello, world");
	}
}
